package com.extJs.demo.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**Servlet 控制器
 * ExtJsServlet.java
 * @author Mercy
 *
 */
@WebServlet(name = "ExtJsServlet", urlPatterns = "/pagingServlet")
public class ExtJsServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static DataService ds = new DataService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		List<User> subLists = new ArrayList<User>();
		
		JSONArray ja;
		JSONObject jo = new JSONObject();
		int start = Integer.valueOf(req.getParameter("start"));
		int limit = Integer.valueOf(req.getParameter("limit"));
		int page = Integer.valueOf(req.getParameter("page"));
		String userName = req.getParameter("userName");
		
		if(userName==null){
			List<User> users = ds.getUserInfo();
			int userSize = users.size();
			System.out.println(start + " " + limit + " " + page);
			userSize = userSize - start;
			if (userSize >= limit) {
				subLists = users.subList(start, start + limit);
			} else {
				subLists = users.subList(start, userSize + start);
			}
			ja = JSONArray.fromObject(subLists);
			jo.put("datas", ja);
			jo.put("total", users.size());
			
		}else{
			List<User> users = ds.getUsersByName(userName);
			int userSize = users.size() - start;
			if (userSize >= limit) {
				subLists = users.subList(start, start + limit);
			} else {
				subLists = users.subList(start, userSize + start);
			}
			ja = JSONArray.fromObject(subLists);
			jo.put("datas", ja);
			jo.put("total", users.size());
		}
		
		
		System.out.println(jo);

		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setContentType("text/html;charset=UTF-8");
		resp.getWriter().print(jo);
		resp.getWriter().close();
		try {
			ds.closeAll();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
